package com.frank.towerrush.adapter;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v4.view.PagerAdapter;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class MapAdapter extends PagerAdapter {
    SparseArray<TextView> views;
    int[] mapsID;
    String[] mapsName;
    Context context;

    public MapAdapter(Context context, int[] mapsID, String[] mapsName) {
        this.context = context;
        this.mapsID = mapsID;
        this.mapsName = mapsName;
        views = new SparseArray<TextView>();
    }

    @Override
    public int getCount() {
        return mapsID.length;
    }

    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
        return arg0 == arg1;
    }

    @Override
    public TextView instantiateItem(ViewGroup container, int position) {
        // 要显示的view
        TextView view = null;

        if (views.get(position) == null) {
            // 没有就新建一个压入表
            view = new TextView(context);
            views.put(position, view);

        } else {
            // 从表中取出
            view = views.get(position);
        }
        // 设置内容
        view.setText(mapsName[position]);
        Drawable map = context.getResources().getDrawable(mapsID[position]);
        map.setBounds(0, 0, map.getMinimumWidth(), map.getMinimumHeight());
        view.setCompoundDrawables(null, null, null, map);
        view.setCompoundDrawablePadding(-100);
        container.addView(view);
        return view;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        // 销毁
        TextView view = views.get(position);
        view.setText("");
        view.setCompoundDrawables(null, null, null, null);
        container.removeView(view);
    }
}
